//
//  AppStateSyncManager.m
//  YuanXinKit
//
//  Created by 晏德智 on 2016/10/26.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "AppStateSyncService.h"
#import <UIKit/UIKit.h>
#import "NSString+Encrypto.h"
#import "GlobalDeviceInfo.h"
#import "NetworkingManager.h"

// yuanxintrack 组件中定义了这个 key，这里复用下
#define kLogCurrentUserIDKey @"YuanXinLogCurrentUserIDKey"

NSString* const tokenStorageKey = @"yuanxinpushToken";
NSString* const voipTokenStorageKey = @"VoidyuanxinpushToken";
NSString* const clientInfoStorageKey = @"clientInfo";

@interface AppStateSyncService()

//@property (nonatomic,strong,readonly) NSDictionary * deviceInfos;

@end

@implementation AppStateSyncService

/*
@synthesize deviceInfos= _deviceInfos;

+(instancetype)shareInstance {
    static dispatch_once_t onceToken;
    static AppStateSyncService *manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (instancetype)init{
    self = [super init];
    if(self){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeStatePostface:) name:UIApplicationWillEnterForegroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeStatePostBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
    return self;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSDictionary *)deviceInfos
{
    if(!_deviceInfos){
        
        _deviceInfos = @{
                         @"SystemName": [GlobalDeviceInfo shareInstance].systemName,//iOS
                         @"SystemVersion": [GlobalDeviceInfo shareInstance].systemVersion,//设备系统版本号10.0
                         @"Model": [GlobalDeviceInfo shareInstance].model,//获取设备详细名称 iphone5s
                         @"Brand": @"Apple",
                         @"DeviceId": [GlobalDeviceInfo shareInstance].uniqueId,
                         @"DeviceLanguage": [GlobalDeviceInfo shareInstance].deviceLocale,//使用语言
                         @"SystemManufacturer":@"IOS",
                         @"TimeZone":[GlobalDeviceInfo shareInstance].timezone,
                         @"AppId":[GlobalDeviceInfo shareInstance].appid,
                         @"ReactNativeVersion":@"",
                         @"Packname":[GlobalDeviceInfo shareInstance].bundleId,
                         @"AppClientVersion":[GlobalDeviceInfo shareInstance].appVersion,
                         @"BuildNumber":[GlobalDeviceInfo shareInstance].buildNumber
                         };
    }
    
    return _deviceInfos;
    
}

//改变状态 去后台
-(void)changeStatePostBackground:(NSNotification *)notification {
    
    [[self class]changeApplicationState:0];
}

//改变状态去前台
-(void)changeStatePostface:(NSNotification *)notification {
    
    [[self class] changeApplicationState:1];
}
 */

//将token 发送到远薪服务器上
+ (void)sendDeviceTokenToServer:(NSData *)deviceToken{
    
    //原来的Token
    NSString *oldToken = [[NSUserDefaults standardUserDefaults] stringForKey:tokenStorageKey];
    /*
     NSMutableString *hexString = [NSMutableString string];
     NSUInteger deviceTokenLength = deviceToken.length;
     const unsigned char *bytes = deviceToken.bytes;
     for (NSUInteger i = 0; i < deviceTokenLength; i++) {
     [hexString appendFormat:@"%02x", bytes[i]];
     }
     
     NSString *token = [hexString copy];
     */
    NSString *token = [[self class] deviceTokenToString:deviceToken];
    
    bool isSend = YES;
    
    if(oldToken){
        if([oldToken isEqualToString:token]){
            isSend =NO;
        }
    }
    
    if(isSend){
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:tokenStorageKey];
        
        
        NSDictionary *dataFilds = @{ @"AppId":[GlobalDeviceInfo shareInstance].appid,
                                     @"PlatForm":@(0),
                                     @"Token":token,
                                     @"DeviceId":[GlobalDeviceInfo shareInstance].uniqueId
                                     };
        
        [[NetworkingManager shareInstance] POST:@"NewPushService/dataColl/coll"
                                     parameters:dataFilds
                                        success:^(NSURLSessionDataTask *task, id responseObject) {
                                            NSLog(@"sendDeviceTokenToServer responseObject %@", responseObject);
                                        } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                                            NSInteger statuscode = response.statusCode;
                                            if(statuscode != 200){
                                                NSLog(@"sendDeviceTokenToServer %s error:%@", __func__,error);
                                            }
                                        }];
    }
}

//将 pushToken 存储在本地
+ (void)saveDeviceToken:(NSData *)deviceToken{
    NSString *token = [[self class] deviceTokenToString:deviceToken];
    if (token && token.length > 0) {
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:tokenStorageKey];
    }
}

//取存储在本地的 pushToken
+ (NSString *)getSavedDeviceToken{
    return [[NSUserDefaults standardUserDefaults] objectForKey:tokenStorageKey];
}

//将 pushToken 发送到远薪服务器上
+ (void)bindingDeviceTokenToServer{
    //TODO:todo->gjs:废弃接口，待删除
    return;
    NSString *token = [AppStateSyncService getSavedDeviceToken];
    if (token && token.length > 0) {
        [AppStateSyncService bindingDeviceTokenToServer:token];
    }
}

//将 pushToken 发送到远薪服务器上
+ (void)bindingDeviceTokenToServer:(NSString *)token{
    //TODO:todo->gjs:废弃接口，待删除
    return;
    if (token && token.length > 0) {
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:tokenStorageKey];
        /*
        {
            "Appid": "{{client_id}}",
            "UserId": "",//留空也意味用户与设备解绑
            "DeviceId": "ffffffff-ad72-aa9d-5470-221947d5c0d8",
            "PushToken": "df69ee35-163b-87ddb8"
        }
         */
        NSString *currentUserID = [[NSUserDefaults standardUserDefaults] objectForKey:kLogCurrentUserIDKey];
        NSDictionary *dataFilds = @{ @"Appid":[GlobalDeviceInfo shareInstance].appid,
                                     @"UserId":currentUserID ?: @"",
                                     @"DeviceId":[GlobalDeviceInfo shareInstance].uniqueId,
                                     @"PushToken":token,
                                     };
        
        [[NetworkingManager shareInstance] POST:@"NewPushService/push/BingdingPushInfo"
                                     parameters:dataFilds
                                        success:^(NSURLSessionDataTask *task, id responseObject) {
                                            NSLog(@"bindingDeviceTokenToServer responseObject %@", responseObject);
                                        } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                                            NSInteger statuscode = response.statusCode;
                                            if(statuscode != 200){
                                                NSLog(@"bindingDeviceTokenToServer %s error:%@", __func__,error);
                                            }
                                        }];
    }
}

//将用户与设备解绑
+ (void)unbindingDeviceTokenToServer:(NSString *)token{
    //TODO:todo->gjs:废弃接口，待删除
    return;
    if (token && token.length > 0) {
        /*
         {
         "Appid": "{{client_id}}",
         "UserId": "",//留空也意味用户与设备解绑
         "DeviceId": "ffffffff-ad72-aa9d-5470-221947d5c0d8",
         "PushToken": "df69ee35-163b-87ddb8"
         }
         */
        NSDictionary *dataFilds = @{ @"Appid":[GlobalDeviceInfo shareInstance].appid,
                                     @"UserId":@"",
                                     @"DeviceId":[GlobalDeviceInfo shareInstance].uniqueId,
                                     @"PushToken":token,
                                     };
        
        [[NetworkingManager shareInstance] POST:@"NewPushService/push/BingdingPushInfo"
                                     parameters:dataFilds
                                        success:^(NSURLSessionDataTask *task, id responseObject) {
                                            NSLog(@"unbindingDeviceTokenToServer responseObject %@", responseObject);
                                        } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                                            NSInteger statuscode = response.statusCode;
                                            if(statuscode != 200){
                                                NSLog(@"unbindingDeviceTokenToServer %s error:%@", __func__,error);
                                            }
                                        }];
    }
}

+ (void)sendDeviceVoipTokenToServer:(NSData *)deviceToken{
    //原来的Token
    NSString *oldToken = [[NSUserDefaults standardUserDefaults] stringForKey:voipTokenStorageKey];
    
    NSString *token = [[self class] deviceTokenToString:deviceToken];
    
    bool isSend = YES;
    
    if(oldToken){
        if([oldToken isEqualToString:token]){
            isSend =NO;
        }
    }
    
    if(isSend){
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:voipTokenStorageKey];
        
        NSDictionary *dataFilds = @{ @"AppId":[GlobalDeviceInfo shareInstance].appid,
                                     @"Token":token,
                                     @"DeviceId":[GlobalDeviceInfo shareInstance].uniqueId
                                     };
        
        [[NetworkingManager shareInstance] POST:@"NewPushService/dataColl/AppleVoIp"
                                     parameters:dataFilds
                                        success:^(NSURLSessionDataTask *task, id responseObject) {
                                            NSLog(@"sendDeviceTokenToServer responseObject %@", responseObject);
                                        } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                                            NSInteger statuscode = response.statusCode;
                                            if(statuscode != 200){
                                                NSLog(@"sendDeviceTokenToServer %s error:%@", __func__,error);
                                            }
                                        }];
        
    }
}
//将客户端的信息收集到服务器
+ (void)sendClientInfoSuccessBlock:(void (^)(id responseObject))successBlock
                              errorBlock:(void (^)(NSError *error))errorBlock{
    
    void (^successResult)(id responseObject) = nil;
    if(successBlock){
        successResult = [successBlock copy];
    }
    
    void (^errorResult)(NSError *error) =nil;
    if(errorBlock){
        errorResult = [errorBlock copy];
    }
    
    NSDictionary *dataFilds = @{
                                @"SystemName": [GlobalDeviceInfo shareInstance].systemName,//iOS
                                @"SystemVersion": [GlobalDeviceInfo shareInstance].systemVersion,//设备系统版本号10.0
                                @"Model": [GlobalDeviceInfo shareInstance].model,//获取设备详细名称 iphone5s
                                @"Brand": @"Apple",
                                @"DeviceId": [GlobalDeviceInfo shareInstance].uniqueId,
                                @"DeviceLanguage": [GlobalDeviceInfo shareInstance].deviceLocale,//使用语言
                                @"SystemManufacturer":@"IOS",
                                @"TimeZone":[GlobalDeviceInfo shareInstance].timezone,
                                @"AppId":[GlobalDeviceInfo shareInstance].appid,
                                @"ReactNativeVersion":@"",
                                @"Packname":[GlobalDeviceInfo shareInstance].bundleId,
                                @"AppClientVersion":[GlobalDeviceInfo shareInstance].appVersion,
                                @"BuildNumber":[GlobalDeviceInfo shareInstance].buildNumber
                                };

    NSMutableString *infs = [[NSMutableString alloc] init];
    
    for (NSString *key in dataFilds) {
        [infs appendFormat:@"@%@",dataFilds[key]];
    }
    
    NSString *encryptoString = [infs sha224];
    NSString *oldInfo = [[NSUserDefaults standardUserDefaults] stringForKey:clientInfoStorageKey];
    bool isSend = YES;
    
    if(oldInfo){
        if([oldInfo isEqualToString:encryptoString]){
            isSend =NO;
        }
    }
    
    if(isSend){
        [[NSUserDefaults standardUserDefaults] setObject:encryptoString forKey:clientInfoStorageKey];
        
        [[NetworkingManager shareInstance] POST:@"NewPushService/deviceInfo/coll"
                                     parameters:dataFilds
                                        success:^(NSURLSessionDataTask *task, id responseObject) {
                                            if(successResult){
                                                successResult(responseObject);
                                            }
                                            NSLog(@"sendDeviceTokenToServer responseObject %@", responseObject);
                                        } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                            
                                            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                                            NSInteger statuscode = response.statusCode;
                                            if(statuscode != 200){
                                                NSLog(@"sendDeviceTokenToServer %s error:%@", __func__,error);
                                                [[NSUserDefaults standardUserDefaults] removeObjectForKey:clientInfoStorageKey];
                                            }
                                            if(errorResult){
                                                errorResult(error);
                                            }
                                        }];
    }else{
        if(successResult){
            successResult(@YES);
        }
        [[self class] changeApplicationState:1 successBlock:^(id responseObject) {
            [[self class] changeApplicationStateSuccessResult:responseObject];
        } errorBlock:^(NSError *error) {
            if(error){
                [[self class] changeApplicationState:1 successBlock:^(id responseObject) {
                    [[self class] changeApplicationStateSuccessResult:responseObject];
                } errorBlock:^(NSError *error) {
                    NSLog(@"sendDeviceTokenToServer %s error:%@", __func__,error);
                }];
            }
        }];
    }
}


+ (void)changeApplicationState:(int)state
                  successBlock:(void (^)(id responseObject))successBlock
                    errorBlock:(void (^)(NSError *error))errorBlock
{
    
    NSDictionary *dataFilds = @{
                                @"State": @(state),
                                @"AppId": [GlobalDeviceInfo shareInstance].appid,
                                @"DeviceId":[GlobalDeviceInfo shareInstance].uniqueId
                                };
    void (^successResult)(id responseObject) = nil;
    if(successBlock){
        successResult = [successBlock copy];
    }
    
    void (^errorResult)(NSError *error) =nil;
    if(errorBlock){
        errorResult = [errorBlock copy];
    }
    
    [[NetworkingManager shareInstance] POST:@"NewPushService/dataColl/changeState"
                                 parameters:dataFilds
                                    success:^(NSURLSessionDataTask *task, id responseObject) {
                                        if(successResult){
                                            successResult(responseObject);
                                        }
                                        NSLog(@"changeApplicationState responseObject %@", responseObject);
                                    } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                        if(errorResult){
                                            errorResult(error);
                                        }
                                        NSLog(@"changeApplicationState %s error:%@", __func__,error);
                                        //[[NSUserDefaults standardUserDefaults] removeObjectForKey:clientInfoStorageKey];
                                    }];
}

+ (NSString *)deviceTokenToString:(NSData *)deviceToken
{
    NSMutableString *result = [NSMutableString string];
    NSUInteger deviceTokenLength = deviceToken.length;
    const unsigned char *bytes = deviceToken.bytes;
    for (NSUInteger i = 0; i < deviceTokenLength; i++) {
        [result appendFormat:@"%02x", bytes[i]];
    }
    
    return [result copy];
}

+ (void)changeApplicationStateSuccessResult:(id)responseObject{
    /*
    if([responseObject isKindOfClass:[NSNumber class]]){
        NSNumber *badgeNumber = responseObject;
        [UIApplication sharedApplication].applicationIconBadgeNumber =[badgeNumber integerValue];
    }
    */
}
@end
